<?php
/**
 * 微博表模型
 */
namespace app\common\model;
use think\Model;
use think\Db;
class Weibo extends Model{

    //指定主键名 系统会自动指定主键id 如果主键不是id名那么则需要像下面一样修改
    protected $pk = 'id';

    public function getListData($where = [],$limit = 10,$order = '') {
        // column() 获取某一列的值 返回数组 一对一关联查询只能查看一条 多条查询并不能用
        // 取出原创微博 目前还是自己发的 没有取关注人的微博 条件肯定不是这个 应该用uid作为条件
        //获取总条数
//        $count = $this->where($where)->count();
        // 排序
        $order = empty($order) ? $order = "time desc" : $order;
        // paginate 获取指定数据 并且分页 alias() 修改表名
        // 指定条件
        $join = [
            ['picture p','w.id=p.wid','LEFT'],
            ['userinfo u','w.uid=u.uid','LEFT'],
        ];
        // 以数组方式 取指定字段 还可以起别名 'u.username' => 'uname'  alias('w') 为表起别名
        $field = [
            'w.*','p.img','p.mini','p.max','p.medium','u.username' => 'uname','u.face','u.weibo','u.face50'
        ];
        // 关联查询
        $objData = $this->alias('w')->join($join)->field($field)->where($where)->order($order)->paginate($limit);
        // 获取分页显示
        $page = $objData->render();
        //组合数据
        $data = [];
        foreach ($objData as $weibo) {
            $data[] = [
                'wid' => $weibo->id,
                'content' => $weibo->content,
                'isturn' => $weibo->isturn,
                'time' => $weibo->time,
                'turn' => $weibo->turn,
                'keep' => $weibo->keep,
                'comment' => $weibo->comment,
                'praise' => $weibo->praise,
                'uid' => $weibo->uid,
                'img' => $weibo->img,
                'username' => $weibo->uname,
                'face' => $weibo->face,
                'weibo' => $weibo->weibo,
                'mini' => $weibo->mini,
                'medium' => $weibo->medium,
                'max' => $weibo->max,
                'face50' => $weibo->face50,
            ];
        }
        //重组结果集，得到转发微博
        if ($data) {
            foreach ($data as $k => $v) {
                if ($v['isturn']) {
                    $tmp = Db::name('Weibo')->alias('w')->join($join)->field($field)->where(['w.id'=>$v['isturn']])->find();
                    $data[$k]['isturn'] = $tmp ? $tmp : '-1';
                }
            }
        }

        //返回数据
        return [
            'data' => $data,
            'page' => $page,
//            'total' => $count
        ];
    }
}